import os
import sys
import time
import configparser
import shutil
import pathlib
import platform
class RegisterTable:
    def _create(self, path):
        with open(path, "w+") as f:
            f.write("")

    def _sync(self,  configobject: configparser.ConfigParser, path):
        with open(path, "w") as f:
            configobject.write(f)
    def _get_data(self, file, section, key):
        cfg = configparser.ConfigParser()
        if not os.path.exists(file): return None
        if pathlib.Path(file).is_dir(): return None
        cfg.read(file)
        if not cfg.has_section(section):
            return None
        return cfg.get(section, key)
    def _set_data(self, file, section, key, value):
        if not os.path.exists(file): return None
        if pathlib.Path(file).is_dir(): return None
        cfg = configparser.ConfigParser()
        cfg.read(file)
        cfg.set(section, key, value)
        self._sync(cfg, file)
    def _delete(self, file, section, key):
        if not os.path.exists(file): return None
        if pathlib.Path(file).is_dir(): return None
        cfg = configparser.ConfigParser()
        cfg.read(file)
        cfg.remove_option(section, key)
        self._sync(cfg, file)
    def __init__(self):

        if platform.system() == "Windows":
            self.full = os.path.join("C:/Users/", os.getlogin(), "cfg.Data")
        else:
            self.full = os.path.join("~/", "cfg.Data")
        if not os.path.exists(self.full):
            os.makedirs(self.full)

        if not os.path.exists(os.path.join(self.full, "main.cfg")):
            self._create(os.path.join(self.full, "main.cfg"))
            maincfg = configparser.ConfigParser()
            maincfg.read(os.path.join(self.full, "main.cfg"))
            if not maincfg.has_section("main"):
                maincfg.add_section("main")
                maincfg.set("main", "path", self.full)
                self._sync(maincfg, os.path.join(self.full, "main.cfg"))
    def makepath(self, pathname):
        '''
        创建一个路径：
        pathname: 路径名
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not os.path.exists(os.path.join(self.full, pathname)):
            pathlib.Path(os.path.join(self.full, pathname)).mkdir(parents=True, exist_ok=True)
            return [0, 'success']
        else:
            return [1, 'path already exists']
    def create_node(self, pathname, mainnode):
        '''
        创建一个节点：
        pathname: 节点路径名
        mainnode: 主节点名
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not os.path.exists(os.path.join(self.full, pathname)):
            return [1, 'path not exists']
        if not mainnode.endswith(".cfg"):
            mainnode += ".cfg"
        self._create(os.path.join(self.full, pathname, mainnode))
        cfg = configparser.ConfigParser()
        cfg.read(os.path.join(self.full, pathname, mainnode))
        if not cfg.has_section("main"):
            cfg.add_section("main")
            self._sync(cfg, os.path.join(self.full, pathname, mainnode))
        return [0, 'success']
    def set_register_data(self, pathname, mainnode, key, value):
        '''
        设置一个节点下的数据：
        pathname: 节点路径名
        mainnode: 主节点名
        key: 注册项
        value: 注册项的值
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not mainnode.endswith(".cfg"):
            mainnode += ".cfg"
        if not os.path.exists(os.path.join(self.full, pathname, mainnode)):
            return [1, 'path or node not exists']
        if self._set_data(os.path.join(self.full, pathname, mainnode), "main", key, value) == None: return [1, 'Unknown error']
        return [0, 'success']

    def get_register_data(self, pathname, mainnode, key):
        '''
        获取一个节点下的数据：
        pathname: 节点路径名
        mainnode: 主节点名
        key: 注册项
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not mainnode.endswith(".cfg"):
            mainnode += ".cfg"
        if not os.path.exists(os.path.join(self.full, pathname, mainnode)):
            return [1, 'path or node not exists']
        if self._get_data(os.path.join(self.full, pathname, mainnode), "main", key) == None: return [1, 'Unknown error']
        return [0, self._get_data(os.path.join(self.full, pathname, mainnode), "main", key)]
    def delete_register_data(self, pathname, mainnode, key):
        '''
        删除一个节点下的数据：
        pathname: 节点路径名
        mainnode: 主节点名
        key: 注册项
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not mainnode.endswith(".cfg"):
            mainnode += ".cfg"
        if not os.path.exists(os.path.join(self.full, pathname, mainnode)):
            return [1, 'path or node not exists']
        self._delete(os.path.join(self.full, pathname, mainnode), "main", key)
        return [0, 'success']
    def delete_node(self, pathname, mainnode):
        '''
        删除一个节点：
        pathname: 节点路径名
        mainnode: 主节点名，需以.cfg结尾
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not mainnode.endswith(".cfg"):
            mainnode += ".cfg"
        if not os.path.exists(os.path.join(self.full, pathname, mainnode)):
            return [1, 'path or node not exists']
        os.remove(os.path.join(self.full, pathname, mainnode))
        return [0, 'success']
    def delete_path(self, pathname):
        '''
        删除一个路径：
        pathname: 节点路径名
        返回值：
        return: [0, 'success'] or [1, 'error']
        '''
        if not os.path.exists(os.path.join(self.full, pathname)):
            return [1, 'path not exists']
        shutil.rmtree(os.path.join(self.full, pathname))
        return [0, 'success']


                
